<template>
  <div class="edit">
    <van-overlay :show="overlayShow" :z-index="1000">
      <div style="display: flex;align-items: center;justify-content: center;height: 100%;">
        <van-loading type="spinner" color="#1989fa">请稍候...</van-loading>
      </div>
    </van-overlay>
    <div style="margin-bottom: 10vh;">
      <van-collapse v-model="activeNames">
        <van-collapse-item v-for="item in jsondata.head" :key="item.grouptitle" :name="item.grouptitle" :title="item.grouptitle">
          <van-cell-group style="border:0px;">
            <div style="border-bottom:1px solid #ebedf0" v-for="itemdata in item.groupvalue" :key="itemdata.ID">
              <idatetime ishead :itemdata="itemdata" v-if="itemdata.sUIType == 'datetime'" />
              <icode ishead :itemdata="itemdata" v-else-if="itemdata.sUIType == 'code'" />
              <ienum ishead :itemdata="itemdata" v-else-if="itemdata.sUIType == 'enum'" :jsondata="jsondata" :idobject="idobject" />
              <iref ishead :itemdata="itemdata" v-else-if="itemdata.sUIType == 'ref'" :clickmodel.sync="clickmodel" :clickfrom.sync="clickfrom" :clickindex.sync="clickindex" :jsondata="jsondata" />
              <ibool ishead :itemdata="itemdata" v-else-if="itemdata.sUIType == 'bool'" :jsondata="jsondata" :idobject="idobject" />
              <ifile ishead :itemdata="itemdata" v-else-if="itemdata.sUIType == 'file'" :jsondata="jsondata" />
              <ipicture ishead :itemdata="itemdata" v-else-if="itemdata.sUIType == 'picture'" :jsondata="jsondata" />
              <istring ishead :itemdata="itemdata" v-else-if="itemdata.sUIType == 'string'" :jsondata="jsondata" :idobject="idobject" />
              <imap ishead :itemdata="itemdata" v-else-if="itemdata.sUIType == 'map'" :jsondata="jsondata" :item="item" />
              <iint ishead :itemdata="itemdata" v-else-if="itemdata.sUIType == 'int'" />
              <idouble ishead :itemdata="itemdata" v-else-if="itemdata.sUIType == 'double'" />
              <idouble ishead :itemdata="itemdata" v-else-if="itemdata.sUIType == 'money'" />
              <istring ishead :itemdata="itemdata" v-else :jsondata="jsondata" :idobject="idobject" />
            </div>
          </van-cell-group>
        </van-collapse-item>
      </van-collapse>
      <div v-for="(itembody, indexName) in jsondata.body" :key="indexName" :name="indexName" :title="indexName">
        <van-collapse v-model="activeBodyNams">
          <van-collapse-item v-for="(item, index) in jsondata.bodydata[indexName]" :key="indexName + index" :name="indexName + index" :title="indexName + (index + 1)">
            <van-cell-group style="border:0px;">
              <div style="border-bottom:1px solid #ebedf0" v-for="itemdata in item" :key="itemdata.ID">
                <idatetime :index="index" :itemdata="itemdata" v-if="itemdata.sUIType == 'datetime'" />
                <icode :index="index" :itemdata="itemdata" v-else-if="itemdata.sUIType == 'code'" />
                <ienum :index="index" :itemdata="itemdata" v-else-if="itemdata.sUIType == 'enum'" :jsondata="jsondata" :idobject="idobject" />
                <iref :index="index" :itemdata="itemdata" v-else-if="itemdata.sUIType == 'ref'" :clickmodel.sync="clickmodel" :clickfrom.sync="clickfrom" :clickindex.sync="clickindex" :jsondata="jsondata" :indexName="indexName" />
                <ibool :index="index" :itemdata="itemdata" v-else-if="itemdata.sUIType == 'bool'" :jsondata="jsondata" :idobject="idobject" />
                <ifile :index="index" :itemdata="itemdata" v-else-if="itemdata.sUIType == 'file'" :jsondata="jsondata" />
                <ipicture :index="index" :itemdata="itemdata" v-else-if="itemdata.sUIType == 'picture'" :jsondata="jsondata" />
                <istring :index="index" :itemdata="itemdata" v-else-if="itemdata.sUIType == 'string'" :jsondata="jsondata" :indexName="indexName" :idobject="idobject" />
                <imap :index="index" :itemdata="itemdata" v-else-if="itemdata.sUIType == 'map'" :jsondata="jsondata" :item="item" />
                <iint :index="index" :itemdata="itemdata" v-else-if="itemdata.sUIType == 'int'" />
                <idouble :index="index" :itemdata="itemdata" v-else-if="itemdata.sUIType == 'double'" />
                <idouble :index="index" :itemdata="itemdata" v-else-if="itemdata.sUIType == 'money'" />
                <istring :index="index" :itemdata="itemdata" v-else :jsondata="jsondata" :indexName="indexName" :idobject="idobject" />
              </div>
              <van-button type="danger" size="mini" round style="float:right;" @click="delRow(indexName, index)">删除</van-button>
            </van-cell-group>
          </van-collapse-item>
        </van-collapse>
        <van-button v-show="jsondata.hasdetail === '1'" type="info" round style="margin-top: 2vh;margin-left: 2vw;" @click="addRow(indexName)">增行</van-button>
      </div>
    </div>
    <van-tabbar v-model="active" safe-area-inset-bottom>
      <van-tabbar-item @click="save">
        <van-button type="info" style="width:25vw">保存</van-button>
      </van-tabbar-item>
      <!-- <van-tabbar-item @click="savesubmit">保存并提交</van-tabbar-item> -->
    </van-tabbar>
  </div>
</template>

<script>
import Vue from 'vue'
import { Search, List, Cell, PullRefresh, Toast, Tabbar, TabbarItem, Popup, DatetimePicker, ActionSheet, Tab, Tabs, Collapse, CollapseItem, Checkbox, CheckboxGroup, Uploader, Overlay, Loading, Rate, NumberKeyboard } from 'vant'
import qs from 'qs'
import useInput from '@/utils/dinuo/useinput'
Vue.use(useInput).use(Search).use(List).use(Cell).use(PullRefresh).use(Toast).use(Tabbar).use(TabbarItem).use(Popup).use(DatetimePicker).use(ActionSheet).use(Tab).use(Tabs).use(Collapse).use(CollapseItem).use(Checkbox).use(CheckboxGroup).use(Uploader).use(Overlay).use(Loading).use(NumberKeyboard).use(Rate)
export default {
  name: 'edit',
  data () {
    return {
      idobject: this.$route.query.idobject,
      jsondata: {},
      index: 0,
      active: 0,
      activeNames: [''],
      activeBodyNams: [''],
      clickmodel: {},
      isLoad: false,
      clickfrom: '',
      clickindex: 0,
      isDisable: false,
      overlayShow: false
    }
  },
  mounted: function () {
    //console.log('edit ...')
    //console.log('start created')
    if (!this.isLoad) {
      let data = { [this.idobject + '_id']: this.$route.query.itemid }
      this.axios({
        method: 'post',
        url: '/api/' + this.idobject + '.edit.do',
        data: qs.stringify(data)
      }).then(res => {
        //console.log(res)
        if (res.data.flag === '1') {
          Toast(res.data.des)
          if (res.data.des && res.data.des.indexOf('登录过期') >= 0) {
            this.loginout()
          }
        } else {
          this.jsondata = res.data.jsondata
          for (let i = 0; i < res.data.jsondata.head.length; i++) {
            let itemgroup = this.jsondata.head[i].groupvalue
            for (let itemindex in itemgroup) {
              let itemdata = itemgroup[itemindex]
              if (itemdata.sUIType === 'datetime' && itemdata.sUITypeExp !== 'long') {
                itemdata.value = itemdata.value.substring(0, 10)
              }
            }
            this.activeNames.push(res.data.jsondata.head[i].grouptitle)
          }
          //console.log(this.jsondata)
          this.isLoad = true
        }
      }).catch(res => {
        this.reserror(res)
      })
    }
  },
  methods: {
    // 结算价设置默认值为0,需校验
    save () {
      if (!this.isDisable) {
        this.overlayShow = true
        this.isDisable = true
        let data = {}
        let cansave = 1
        data[this.idobject + '_id'] = this.$route.query.itemid
        for (let groupindex in this.jsondata.head) {
          let itemgroup = this.jsondata.head[groupindex].groupvalue
          for (let itemindex in itemgroup) {
            let itemdata = itemgroup[itemindex]
            if (itemdata.sUIType === 'ref') {
              data[itemdata.idObject + '_' + itemdata.sField] = itemdata.valuehidden
              data[itemdata.idObject + '_' + itemdata.sField + '_ref'] = itemdata.value
            } else if (itemdata.sUIType === 'enum') {
              data[itemdata.idObject + '_' + itemdata.sField] = itemdata.valuehidden
              data[itemdata.idObject + '_' + itemdata.sField + '_enum'] = itemdata.value
            } else if (itemdata.sUIType === 'file' || itemdata.sUIType === 'picture') {
              data[itemdata.idObject + '_' + itemdata.sField] = itemdata.valuehidden
              data[itemdata.idObject + '_' + itemdata.sField + '_title'] = itemdata.value
            } else {
              data[itemdata.idObject + '_' + itemdata.sField] = itemdata.value
            }
          }
        }
        if (this.jsondata.hasdetail === '1') {
          for (let indexName in this.jsondata.bodydata) {
            let typeValue = ''
            let price2Value = 0
            let istype = false
            let isprice2 = false
            for (let i = 0; i < this.jsondata.bodydata[indexName].length; i++) {
              let item = this.jsondata.bodydata[indexName][i]

              for (let itemindex in item) {
                let itemdata = item[itemindex]

                if (itemdata.sUIType === 'ref') {
                  if (itemdata.lMustInput === '1' && itemdata.value === '') {
                    itemdata.errormsg = '不能为空'
                    cansave = 0
                  }
                  data[i + '_' + itemdata.idObject + '_' + itemdata.sField] = itemdata.valuehidden
                  data[i + '_' + itemdata.idObject + '_' + itemdata.sField + '_ref'] = itemdata.value
                } else if (itemdata.sUIType === 'enum') {
                  if (itemdata.lMustInput === '1' && itemdata.value === '') {
                    itemdata.errormsg = '不能为空'
                    cansave = 0
                  }
                  data[i + '_' + itemdata.idObject + '_' + itemdata.sField] = itemdata.valuehidden
                  data[i + '_' + itemdata.idObject + '_' + itemdata.sField + '_enum'] = itemdata.value
                } else {
                  if (itemdata.lMustInput === '1' && itemdata.value === '') {
                    itemdata.errormsg = '不能为空'
                    cansave = 0
                  }
                  data[i + '_' + itemdata.idObject + '_' + itemdata.sField] = itemdata.value
                }

                if (itemdata.sField == 'type') {
                  typeValue = itemdata.value
                  if (typeValue == '药品') {
                    //console.log('type...', '药品', ' true')
                    istype = true
                  } else {
                    //console.log('type...', '赠品 或 礼品及物料', ' false')
                    istype = false
                  }
                }
                if (itemdata.sField == 'price2') {
                  //console.log('price2...')
                  price2Value = itemdata.value
                  //console.log('price2Value', price2Value)
                  if (price2Value && (price2Value == '0' || price2Value == '0.0' || price2Value == '0.00')) {
                    //console.log('price2...', '结算价为0')
                    isprice2 = true
                  } else {
                    isprice2 = false
                  }
                }
              }
            }
            //console.log('istype:', istype, 'isprice2:', isprice2)
            if (istype && isprice2) {
              Toast('报量类型为药品,结算价不能为0')
              this.isDisable = false
              this.overlayShow = false
              return
            }
            typeValue = ''
            price2Value = 0
            istype = false
            isprice2 = false
          }
        }
        //console.log('jsondata', this.jsondata)
        if (cansave === 0) {
          this.isDisable = false
          this.overlayShow = false
          Toast('请检查必输项!')
          return
        }

        this.axios({
          method: 'post',
          url: '/api/' + this.idobject + '.editsave.do',
          data: qs.stringify(data)
        }).then(res => {
          this.isDisable = false
          this.overlayShow = false
          if (res.data.flag === '0') {
            Toast('保存成功')
            if (this.$route.query.fromobject && this.$route.query.fromcardid) {
              this.$router.push({ name: 'card', query: { idobject: this.$route.query.fromobject, itemid: this.$route.query.fromcardid } })
            } else {
              this.$router.push({ name: 'list', query: { idobject: this.idobject } })
            }
          } else {
            Toast(res.data.des)
            if (res.data.des && res.data.des.indexOf('登录过期') >= 0) {
              this.loginout()
            }
          }
          //console.log(res)
        }).catch(res => {
          this.isDisable = false
          this.overlayShow = false
          //console.log(res)
        })
      }
    },
    savesubmit () {
      Toast('submit')
    },
    addRow (indexName) {
      // 不是本月的细单不允许加行
      // let projectData = require('@/project.json')
      // if (projectData.project && projectData.project == 'dinuo/') {
      //   for (let groupindex in this.jsondata.head) {
      //     let itemgroup = this.jsondata.head[groupindex].groupvalue
      //     for (let itemindex in itemgroup) {
      //       let itemdata = itemgroup[itemindex]
      //       if (itemdata.sField == 'date') {
      //         let value = itemdata.value
      //         //console.log('value', value)
      //         let paramDate = new Date(value)
      //         let currentDate = new Date()
      //         if (paramDate.getFullYear() != currentDate.getFullYear() || paramDate.getMonth() != currentDate.getMonth()) {
      //           Toast('非当前月,不能新增明细')
      //           return
      //         }
      //       }
      //     }
      //   }
      // }

      let bodycopy = JSON.parse(JSON.stringify(this.jsondata.body[indexName]))
      this.jsondata.bodydata[indexName].push(bodycopy)
    },
    delRow (indexName, index) {
      if (this.jsondata.bodydata[indexName].length === 1) {
        Toast('至少保留一条表体行，不能删除！')
        return
      }
      this.jsondata.bodydata[indexName].splice(index, 1)
    }
  },
  activated () {
    //console.log(this.$store.state.ref_show)
    //console.log(this.$store.state.ref_id)
    if (this.$store.state.ref_show !== '') {
      this.clickmodel.value = this.$store.state.ref_show
      this.clickmodel.valuehidden = this.$store.state.ref_id
      let fieldmap = this.clickmodel.fieldmap
      if (fieldmap !== undefined && fieldmap.length > 0) {
        let arrFieldmap = fieldmap.split(';')
        let item = this.$store.state.ref_item
        if (this.clickfrom === 'headdata') {
          for (let groupindex = 0; groupindex < this.jsondata.head.length; groupindex++) {
            let itemgroup = this.jsondata.head[groupindex]
            for (let itemindex = 0; itemindex < itemgroup.groupvalue.length; itemindex++) {
              let itemdata = itemgroup.groupvalue[itemindex]
              for (let fieldmapindex in arrFieldmap) {
                let arrFieldMapKey = arrFieldmap[fieldmapindex].split(':')
                if (this.$store.state.ref_field === arrFieldMapKey[1]) {
                  continue
                }
                if (arrFieldMapKey.length === 3 && arrFieldMapKey[2] !== '' && this.$store.state.ref_field !== arrFieldMapKey[2]) {
                  continue
                }
                if (itemdata.sField === arrFieldMapKey[1]) {
                  if (itemdata.sUIType === 'ref') {
                    itemdata.value = item[arrFieldMapKey[0] + '_ref']
                    itemdata.valuehidden = item[arrFieldMapKey[0]]
                  } else if (itemdata.sUIType === 'enum') {
                    itemdata.value = item[arrFieldMapKey[0] + '_enum']
                    itemdata.valuehidden = item[arrFieldMapKey[0]]
                  } else {
                    itemdata.value = item[arrFieldMapKey[0]]
                  }
                }
              }
            }
          }
        } else if (this.clickfrom === 'bodydata') {
          for (let itemindex in this.jsondata.bodydata[this.clickindex]) {
            let itemdata = this.jsondata.bodydata[this.clickindex][itemindex]
            for (let fieldmapindex in arrFieldmap) {
              let arrFieldMapKey = arrFieldmap[fieldmapindex].split(':')
              if (this.$store.state.ref_field === arrFieldMapKey[1]) {
                continue
              }
              if (arrFieldMapKey.length === 3 && arrFieldMapKey[2] !== '' && this.$store.state.ref_field !== arrFieldMapKey[2]) {
                continue
              }
              if (itemdata.sField === arrFieldMapKey[1]) {
                if (itemdata.sUIType === 'ref') {
                  itemdata.value = item[arrFieldMapKey[0] + '_ref']
                  itemdata.valuehidden = item[arrFieldMapKey[0]]
                } else if (itemdata.sUIType === 'enum') {
                  itemdata.value = item[arrFieldMapKey[0] + '_enum']
                  itemdata.valuehidden = item[arrFieldMapKey[0]]
                } else {
                  itemdata.value = item[arrFieldMapKey[0]]
                }
              }
            }
          }
        }
      }
      this.clickmodel = {}
      this.clickindex = 0
      this.clickfrom = ''
      this.$store.commit('clearRef')
    }
  }
}
</script>

<style>
.fieldgroup_title {
  text-align: left;
  margin: 0px;
  padding: 25px 15px 15px;
  color: rgba(69, 90, 100, 0.6);
  font-weight: normal;
  font-size: 14px;
}
</style>
